package handlers

import (
	"git.hortorgames.com/serverless/htgserver/apiserver"
	"git.hortorgames.com/serverless/htgserver/apiserver/session"
	"git.hortorgames.com/serverless/htgserver/consts"
)

type MidVerifySession struct {
	Base
}

func NewMidVerifySession(server *apiserver.Server) *MidVerifySession {
	h := &MidVerifySession{}
	h.Server = server
	return h
}

//@httpMid:""
func (h *MidVerifySession) Verify(ctx *apiserver.Context) {
	if ctx.Request().Method != "POST" {
		ctx.Next()
		return
	}
	if ctx.RequestData.PlayerId == 0 || ctx.RequestData.Token == "" {
		ctx.Logger().Error(`Verify failed, req.PlayerId == 0 || req.Token == ""`)
		h.Halt(ctx, consts.ErrorMissParameter)
		ctx.Abort()
		return
	}

	sess := ctx.StartRedisSession()
	defer sess.End()
	valid, _, err := session.CheckToken(sess, ctx.RequestData.PlayerId, ctx.RequestData.Token)
	if err != nil {
		ctx.Logger().Error(`CheckToken error`, "err", err.Error())
		h.Halt(ctx, consts.ErrorInternalError)
		ctx.Abort()
		return
	}
	if !valid {
		ctx.Logger().Error(`Token is invalid`)
		h.Halt(ctx, consts.ErrorVerifyError)
		ctx.Abort()
		return
	}
	ctx.Next()
}
